/*
 * Copyright (C) 2011 CrystalRange
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.crystalrange.help.web;

import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.TreeitemRenderer;

public class HelpTreeRenderer implements TreeitemRenderer {
    
    public void render(Treeitem item, Object data, int i) throws Exception {
        if (data instanceof HelpFolderTreeNode) {
            this.renderHelpFolderTreeNode(item, (HelpFolderTreeNode) data);
        }
        if (data instanceof HelpItemTreeNode) {
            this.renderHelpItemTreeNode(item, (HelpItemTreeNode) data);
        }
    }

    private void renderHelpFolderTreeNode(Treeitem item, HelpFolderTreeNode helpFolderTreeNode) throws Exception {
        item.setValue(helpFolderTreeNode);
        item.setId("helpFolderTreeNode" + helpFolderTreeNode.getId());
        item.setLabel(helpFolderTreeNode.getName());
        item.setTooltiptext(helpFolderTreeNode.getDescription());
        item.setImage("/img/book.png");
        item.addEventListener(Events.ON_OPEN, new HelpFolderListener(item));

        Session session = Sessions.getCurrent();
        if (session.getAttribute(item.getId()) != null) {
            item.setOpen((Boolean) session.getAttribute(item.getId()));
        }
    }

    private void renderHelpItemTreeNode(Treeitem item, HelpItemTreeNode helpItemTreeNode) throws Exception {
        item.setValue(helpItemTreeNode);
        item.setId("helpItemTreeNode" + helpItemTreeNode.getId());
        item.setLabel(helpItemTreeNode.getName());
        item.setTooltiptext(helpItemTreeNode.getDescription());
        item.setImage("/img/page_white_text.png");
    }
}
